<template>
  <div>
    <!-- 1.0 头部导航结构 -->
    <van-nav-bar
      title="我的关注"
      left-arrow
      @click-left="$router.back()"
      @click-right="$router.push({ path: '/' })"
    >
      <template #right>
        <van-icon name="wap-home-o" color="#f00" size="6vw" />
      </template>
    </van-nav-bar>

    <!-- 2.0 关注列表 -->
    <div class="list">
      <div class="item" v-for="(item, index) in follows" :key="item.id">
        <van-image class="avatar" :src="item.head_img | imgUrl"></van-image>
        <div class="info">
          <h4 class="username">{{ item.nickname }}</h4>
          <p class="date">{{ item.create_date | formatDate }}</p>
        </div>
        <div
          class="btn"
          :class="{ danger: !item.isFollow }"
          @click="followBtn(item.id, index)"
        >
          {{ item.isFollow ? "取消关注" : "添加关注" }}
        </div>
      </div>
    </div>
    <!-- 如果列表为空 - 展示空状态 -->
    <van-empty v-if="!follows.length" description="关注空空如也" />
  </div>
</template>

<script>
import {
  getUserFollowsAPI,
  userFollowsByIdAPI,
  userUnFollowsByIdAPI,
} from "../apis/user";
export default {
  data() {
    return {
      follows: [],
    };
  },
  async created() {
    const res = await getUserFollowsAPI();
    // console.log(res);
    this.follows = res.data.data.map((item) => {
      return { ...item, isFollow: true };
    });
  },
  methods: {
    async followBtn(id, index) {
      // console.log("用户的id", id, index);
      const { isFollow } = this.follows[index];
      // 如果是已经关注 - 取消关注
      if (isFollow) {
        const res = await userUnFollowsByIdAPI(id);
        // console.log(1111, res);
      } else {
        const res = await userFollowsByIdAPI(id);
        // console.log(1111, res);
      }
      // 改变关注状态
      this.follows[index].isFollow = !this.follows[index].isFollow;
    },
  },
};
</script>

<style lang="less" scoped>
.list {
  .item {
    height: 80px;
    border-bottom: 1px solid #ddd;
    display: flex;
    align-items: center;
    padding: 0 20px;
    .avatar {
      width: 40px;
      height: 40px;
    }
    .info {
      flex: 1;
      margin-left: 20px;
      .username {
        font-size: 16px;
      }
      .date {
        font-size: 13px;
        margin-top: 5px;
        color: #666;
      }
    }
    .btn {
      width: 75px;
      line-height: 30px;
      text-align: center;
      background-color: #e1e1e1;
      border-radius: 50px;
      font-size: 12px;
    }
    .danger {
      background-color: red;
      color: #fff;
    }
  }
}
</style>